﻿//-----------------------------------------------------------------------
// <copyright file="Vector2D.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Common.Math
{
    using System;

    /// <summary>
    /// 2D vector structure.
    /// </summary>
    public struct Vector2D
    {
        #region Fields - Public

        /// <summary>
        /// X component of the vector.
        /// </summary>
        public float x;

        /// <summary>
        /// Y component of the vector.
        /// </summary>
        public float y;

        #endregion

        #region Constructor

        /// <summary>
        /// Constructs a vector from components.
        /// </summary>
        /// <param name="tx">Vector x component.</param>
        /// <param name="ty">Vector y component.</param>
        public Vector2D(float tx, float ty)
        {
            this.x = tx;
            this.y = ty;
        }

        #endregion

        #region Properties - Public static

        /// <summary>
        /// Gets the zero vector.
        /// </summary>
        public static Vector2D Zero
        {
            get
            {
                return new Vector2D(0.0f, 0.0f);
            }
        }

        /// <summary>
        /// Gets the one vector.
        /// </summary>
        public static Vector2D One
        {
            get
            {
                return new Vector2D(1.0f, 1.0f);
            }
        }

        /// <summary>
        /// Gets the unit x axis.
        /// </summary>
        public static Vector2D AxisX
        {
            get
            {
                return new Vector2D(1.0f, 0.0f);
            }
        }

        /// <summary>
        /// Gets the unit y axis.
        /// </summary>
        public static Vector2D AxisY
        {
            get
            {
                return new Vector2D(0.0f, 1.0f);
            }
        }

        #endregion

        #region Operator overloads

        /// <summary>
        /// Add two vectors together and return the result.
        /// </summary>
        /// <param name="lhs">Left hand side vector.</param>
        /// <param name="rhs">Right hand side vector.</param>
        /// <returns>Returns lhs + rhs.</returns>
        public static Vector2D operator +(Vector2D lhs, Vector2D rhs)
        {
            return new Vector2D(lhs.x + rhs.x, lhs.y + rhs.y);
        }

        /// <summary>
        /// Subtract two vectors and return the result.
        /// </summary>
        /// <param name="lhs">Left hand side vector.</param>
        /// <param name="rhs">Right hand side vector.</param>
        /// <returns>Returns lhs - rhs.</returns>
        public static Vector2D operator -(Vector2D lhs, Vector2D rhs)
        {
            return new Vector2D(lhs.x - rhs.x, lhs.y - rhs.y);
        }

        /// <summary>
        /// Multiply a vector by a float.
        /// </summary>
        /// <param name="lhs">Left hand side vector.</param>
        /// <param name="rhs">Right hand side float.</param>
        /// <returns>Returns lhs - rhs.</returns>
        public static Vector2D operator *(Vector2D lhs, float rhs)
        {
            return new Vector2D(lhs.x * rhs, lhs.y * rhs);
        }

        /// <summary>
        /// Negation operator.
        /// </summary>
        /// <param name="rhs">Vector to negate.</param>
        /// <returns>Returns -rhs.</returns>
        public static Vector2D operator -(Vector2D rhs)
        {
            return new Vector2D(-rhs.x, -rhs.y);
        }

        #endregion

        #region Methods - Public static

        /// <summary>
        /// Attempt to parse a vector from the passed string.
        /// </summary>
        /// <param name="value">String to parse a vector from.</param>
        /// <param name="vec">Destination vector.</param>
        /// <returns>Returns true if the vector was parsed successfully.</returns>
        public static bool TryParse(string value, out Vector2D vec)
        {
            vec = Vector2D.Zero;

            if (string.IsNullOrEmpty(value))
            {
                return false;
            }

            string[] parts = value.Split(' ');
            if (parts == null || parts.Length != 2)
            {
                return false;
            }

            bool success = true;

            success &= float.TryParse(parts[0], out vec.x);
            success &= float.TryParse(parts[1], out vec.y);

            return success;
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Computes the dot product between this vector and the passed vector.
        /// </summary>
        /// <param name="rhs">Right hand side vector.</param>
        /// <returns>Returns the dot product of the two vectors.</returns>
        public float Dot(Vector2D rhs)
        {
            return (this.x * rhs.x) + (this.y * rhs.y);
        }

        /// <summary>
        /// Compute the length squared of the vector.
        /// </summary>
        /// <returns>Returns the length squared of the vector.</returns>
        public float LengthSq()
        {
            return this.Dot(this);
        }

        /// <summary>
        /// Compute the length of the vector.
        /// </summary>
        /// <returns>Returns the length of the vector.</returns>
        public float Length()
        {
            return (float)System.Math.Sqrt(this.LengthSq());
        }

        /// <summary>
        /// Unitize the vector. If we can't, return the passed vector.
        /// </summary>
        /// <param name="vec">Vector to use if we can't unitize this vector.</param>
        /// <returns>Returns this vector as a unit vector or the safe passed vector.</returns>
        public Vector2D SafeUnitOrVec(Vector2D vec)
        {
            float lenSq = this.LengthSq();

            if (lenSq < MathUtility.Epsilon)
            {
                return vec;
            }

            return this * (1.0f / (float)System.Math.Sqrt(lenSq));
        }

        /// <summary>
        /// Computes the distance squared between this vector and the passed vector.
        /// </summary>
        /// <param name="vec">Vector to compute the distance with.</param>
        /// <returns>Returns the distance squared between this vector and the passed vector.</returns>
        public float DistanceSq(Vector2D vec)
        {
            Vector2D diff = vec - this;

            return MathUtility.Square(diff.x) + MathUtility.Square(diff.y);
        }

        /// <summary>
        /// Convert object to string.
        /// </summary>
        /// <returns>Returns a string representation of the object.</returns>
        public override string ToString()
        {
            return string.Format("{0} {1}", this.x, this.y);
        }

        #endregion
    }
}
